package com.chc.finance.sys.dao;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.aspectj.weaver.patterns.IScope;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.chc.finance.sys.vo.User;
import com.mongodb.WriteResult;

public class BaseDao {
	@Resource
	protected MongoTemplate mongoTemplate;
	
	public <T> Object findById(Object id, Class<T> t) {
		return mongoTemplate.findById(id, t, t.getSimpleName());
	}
	
	public <T> List<T> findAll(Class<T> t) {
		List<T> list=mongoTemplate.findAll(t, t.getSimpleName());
		return list;
	}
	public void save(Object obj) {
		String clsName=obj.getClass().getSimpleName();
		if (! mongoTemplate.collectionExists(clsName)){
			System.out.println("create");
			mongoTemplate.createCollection(clsName);
		}
		mongoTemplate.save(obj, obj.getClass().getSimpleName());
	}
	
	public <T> void deleteObjById(Integer id, Class<T> t) {
		mongoTemplate.remove(new Query(Criteria.where("id").is(id)), t);
	}
	
	public <T> WriteResult update( Map<String,Object> whereMap,Map<String,Object> valueMap,Class<T> t){
		Query query = new Query();
		Update update= new Update();
		for (String key:whereMap.keySet()){
			query.addCriteria(Criteria.where("name").is("test5"));
		}
		System.out.println(mongoTemplate.find(query, t).size());
		for (String key:valueMap.keySet()){
			update.addToSet(key, valueMap.get(key));
		}
		return mongoTemplate.updateMulti(query, update, t);
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	public void createCollection(Class cls) {
		if (!mongoTemplate.collectionExists(cls)) {
			mongoTemplate.createCollection(cls);
		}
		
	}

	public void dropCollection(Class cls) {
		for(String name:mongoTemplate.getCollectionNames()){
			System.out.println(name);
		}
		if (mongoTemplate.collectionExists(cls)) {
			mongoTemplate.dropCollection(cls);
		}
		
	}
	
}
